/* 
 * @name login.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */

var gblFields = [
    'property_group_id',
    'location_id',
    'loc_region',
    'property_group_type_id',
    'property_group_sub_type_id',
    'property_reg_no',
    'type_of_ownership',
    'owners_name',
    'other_partners_name',
    'house_no',
    'address',
    'telephone',
    'business_no',
    'nationality',
    'location',
    'popular_area_name',
    'street_name',
    'area_code',
    'comment',
    'private_property',
    'identification',
    'name',
    'type_of_business',
    'registration_no',
    'year_of_establishment',
    'dormant_business',
    'permit_no',
    'store_no',
    'no_rooms',
    'date_approval',
    'clasification',
    'no_trained_teachers',
    'no_nontrained_teachers',
    'no_class_room',
    'no_students_per_class'
]
 
var Report = {
	
    location_name:'',
    account_report_type:'',
    report_group_id:'',
    report_group_name:'',
    
    init: function(){
        
        $('#AcctReportTypeDebtors').attr('checked','checked');
        $('#AcctReportTypeDebtors').click(function(){
            $('#revenue_year_select').hide();
        });
        $('#AcctReportTypeRevenue').click(function(){
            $('#revenue_year_select').show();
        });
        
        $('#location_id').change(function(){
            Report.location_name =  $("#location_id option:selected").text();
            Report.getData(parseInt($(this).val()),'property');
        });
        $('#location_id').change();
        
       /* $('#acct_location_id').change(function(){
            Report.location_name =  $("#acct_location_id option:selected").text();
            Report.account_report_type = $("input[name='acct_report_type']:checked").val();
            Report.getData(parseInt($(this).val()),'account');
        }); */
        
        $('#acct-report-btn').click(function(){
            Report.location_name =  $("#acct_location_id option:selected").text();
            var loc_id =  $("#acct_location_id").val();
            Report.report_group_id = $("#acct_group_id").val();
            Report.report_group_name = $("#acct_group_id option:selected").text();
            Report.account_report_type = $("input[name='acct_report_type']:checked").val();
            Report.getData(parseInt(loc_id),'account');
        });
        
        
        $('a.view_list_properties').live('click',function(){
            var ids = $(this).siblings('.prop_ids').val();
            var title = $(this).siblings('.title').val();
            var group_id = $(this).siblings('.group_id').val();
            if(ids){
                Report.viewData(ids, title, group_id);
            }
        });
        
        $('a.print_list_properties').live('click',function(){
            var ids = $(this).siblings('.prop_ids').val();
            var title = $(this).siblings('.title').val();
            var group_id = $(this).siblings('.group_id').val();
            if(ids){
                Report.printData(ids, title, group_id);
            }
        });
        
        /** Acordion Content Initializer **/
         $('#report_type_accordion').hoverAccordion({
            keepHeight : true, 
            onClickOnly : true,
            activateItem: 1
         });
         
         /** Bind buttom live for Print **
         $('#print-debtors-btn').live('click',function(){
              var location_name =  $("#acct_location_id option:selected").text();
              var loc_id = $('#acct_location_id').val();
              Report.report_group_id = $("#acct_group_id").val();
              Report.report_group_name = $("#acct_group_id option:selected").text();
              Report.printRevenueDebtors(loc_id, 'debtors', location_name, '');
         });*/
         $('#print-acct-btn').click(function(){
              var location_name =  $("#acct_location_id option:selected").text();
              var loc_id = $('#acct_location_id').val();
              var year = $('#revenue_year').val();
              Report.account_report_type = $("input[name='acct_report_type']:checked").val();
              Report.report_group_id = $("#acct_group_id").val();
              Report.report_group_name = $("#acct_group_id option:selected").text();
    
              Report.printRevenueDebtors(loc_id, Report.account_report_type, location_name, year); 
         });
    },
    
    getData: function(id, type){
        var query = 'id='+ id+
            '&location_name='+Report.location_name+
            '&group_id='+Report.report_group_id+
            '&group_name='+Report.report_group_name+
            '&acct_report_type='+Report.account_report_type+
            '&revenue_year='+$('#revenue_year').val()+
            '&type='+type;
        var url  = $('#get-data-url').val();
        /* Send the data to the server and handle the server response */
        $.post(url, query, function(response){
           $('.report_views').html(response);
           //console.log(response)
           /** Tree **/
           if(type == 'property'){ //console.log(gblfrmtData);
            	$("#report_tree").treeview({
            		//collapsed: true,
            		animated: "fast",
            		persist: "location",
                    unique: true
            	});
                
                var tle = 'Property shares at, '+Report.location_name;
                //console.log(gblfrmtData);
                var data_arr = new Array();
                var chk = 0;
                for(var ddt in gblfrmtData){
                    if(chk == 0){
                        var x = {
                        	name: gblfrmtData[ddt].name,    
    						y: gblfrmtData[ddt].item_count,
    						sliced: true,
    						selected: true
                        };
                    }
                    else{
                        var x = new Array();
                        x.push(gblfrmtData[ddt].name);
                        x.push(gblfrmtData[ddt].item_count);
                    }
                    
                    data_arr.push(x);
                    
                    chk++;
                }
                
                var chartObj = {
    				type: 'pie',
    				name: 'Revenue share',
    				data: data_arr,
                    credits:false
    			}
                Report.chartData(chartObj, tle);
           }
           else{ // Account
                if(Report.account_report_type == 'debtors'){
                     $('table.list-table-data tbody tr:even').addClass('table_zebra'); 
                     $('#chart_views').html('');
                }
                else{// Revenue
                    var tle = 'Revenue shares from, '+Report.report_group_name+' at, '+Report.location_name+' for year, '+$('#revenue_year').val();
                    //console.log(gblfrmtData);
                    var chartObj = {
        				type: 'pie',
        				name: 'Revenue share',
        				data: [
        					['Expected Revenue',  parseFloat(gblfrmtData['bill_totals'])],
        					['Actual Revenue',    parseFloat(gblfrmtData['bill_payment_totals'])],
        					{
        						name: 'Deficit',    
        						y: parseFloat(gblfrmtData['bill_debit_totals']),
        						sliced: true,
        						selected: true
        					}
        				]
        			}
                    Report.chartData(chartObj, tle);
                }
           }
       },'html');
    },
    
    
    viewData: function(ids, title, group_id){
        var url = $('#view-data-url').val();
        var query = 'ids=' + ids+'&group_id='+group_id;
        $.post(url, query, function(response){ 
            
               $("#property_colorbox").html(response);
               
               $('table#list-table-data tbody tr:even').addClass('table_zebra');  
               
               $.colorbox({
                 inline:true,
                 scrolling:false,
                 overlayClose:false,
                 escKey:false,
                 title:title+' At '+Report.location_name,
                 href:"#property_colorbox",
                 width:"75%", 
                 height:"50%"
              });
              
              $.colorbox.resize();
              
        },'html');
    },
    
    
    printData: function(ids, title, group_id){
        
        $("#formIds").val(ids);
        $("#formTitle").val(title+' At '+Report.location_name);
        $("#formGroupid").val(group_id);
        $("#formLocationName").val(Report.location_name);
        
        window.open('',"PrintWindow","menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        document.getElementById('popUpform').submit();
        
       // var query = 'group_id='+group_id+'&title='+title+' At '+Report.location_name+'&ids=' + ids;
       // var url = $('#print-data-url').val()+'&'+query;
       //window.open(url,"PrintWindow","menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
    },
    
    printRevenueDebtors: function(id, type, loc_name, year){            
        var query = 'id='+id+'&type='+type+'&location_name='+loc_name+'&year='+year+'&group_id='+Report.report_group_id+'&group_name='+Report.report_group_name;
        var url = $('#print-revenue-debtor-url').val()+'?'+query;
        window.open(url,"PrintWindow","menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
    },
    
    
    chartData: function(data_series, title){
        chart = new Highcharts.Chart({
			chart: {
				renderTo: 'chart_views',
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false
			},
			title: {
				text: title
			},
			tooltip: {
				formatter: function() {
					return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(1) +' %';
				}
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					dataLabels: {
						enabled: true,
						color: '#ffffff',
						connectorColor: '#ffffff',
						formatter: function() {
							return '<b>'+ this.point.name +'</b>: '+ this.percentage.toFixed(1) +' %';
						}
					}
				}
			},
		    series: [data_series]
		});
    }
   
};

/* when the page is loaded */
$(document).ready(function() {
	Report.init();
});